<?php

namespace app\admin\model;

use think\Model;

/**
 * Device
 */
class Device extends Model
{
    // 表名
    protected $name = 'device';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = true;
    protected $updateTime = false;


    const HEARTBEAT_EXPIRE = 3600;

    protected $append = [
        'online_status'
    ];


    protected static function onAfterInsert($model): void
    {
        if (is_null($model->weigh)) {
            $pk = $model->getPk();
            if (strlen($model[$pk]) >= 19) {
                $model->where($pk, $model[$pk])->update(['weigh' => $model->count()]);
            } else {
                $model->where($pk, $model[$pk])->update(['weigh' => $model[$pk]]);
            }
        }
    }

    
    public function getOnlineStatusAttr( ){
        
        if(!empty($this->heartbeat_time)){
            $heartbeatTime = strtotime($this->heartbeat_time);
            $now = time();
            if($now - $heartbeatTime > self::HEARTBEAT_EXPIRE){
                // 超出心跳时间
                return  false;
            }
        }
        return true;
    }

    
}